package com.yx.cloud.activity;

import android.app.Dialog;
import android.content.Intent;
import android.content.res.Resources;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.iot.base.service.req.LoginParam;
import com.iot.base.service.resp.LoginResponse;
import com.iot.sweeper.AppContext;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.yx.cloud.R;
import com.yx.cloud.base.BaseActivity;
import com.yx.cloud.bean.CountryCodeBean;
import com.yx.cloud.constant.Constants;
import com.yx.cloud.country.CountryActivity;
import com.yx.cloud.databinding.LoginActivityBinding;
import com.yx.cloud.utils.AtyContainer;
import com.yx.cloud.utils.CountryCodeUtils;
import com.yx.cloud.utils.DialogUtils;
import com.yx.cloud.utils.Intent_utils;
import com.yx.cloud.utils.LanguageUtils;
import com.yx.cloud.utils.LoadProgressDialog;
import com.yx.cloud.utils.RomUtils;
import com.yx.cloud.utils.SharedPrefsUtil;
import com.yx.cloud.utils.ToastUtil;
import com.iot.common.utils.Event;
import com.iot.common.utils.LogUtils;

import java.util.ArrayList;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;


/**
 * 创建时间 : 2018/12/25.
 * 创建人 :
 * 功能描述 :
 */
public class LoginActivity extends BaseActivity implements View.OnClickListener {
    private static final String TAG = "LoginActivity";
    private String phoneOrEmail;
    private String username;
    private LoadProgressDialog loadProgressDialog;
    // 微信登录
    private static IWXAPI WXapi;
    private LoginActivityBinding binding;
    private String mCountryCode;
    private Dialog policyPrivacy_dialog;

    @Override
    public void onCreate() {
        binding = LoginActivityBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        EventBus.getDefault().register(this);
        initData();
    }

    private void initData() {
        //自动获取当前国家代码
        // String contryCode = CountryCodeUtils.getCountryZipCode(this);
        String systemLanguage = LanguageUtils.getSystemLanguage(this);
        String substring = systemLanguage.substring(3, 5);
        ArrayList<CountryCodeBean> codeList = CountryCodeUtils.getCountryCodeList(this);
        for (int i = 0; i < codeList.size(); i++) {
            if (substring.equals("" + codeList.get(i).getLocale())) {
                String countryName = codeList.get(i).getName();
                LogUtils.i(codeList.get(i).getCode() + ": tvCountryCode :" + codeList.get(i).getName());
                binding.tvCountrycodeCode.setText(countryName);
                mCountryCode = codeList.get(i).getCode() + "";
            }
        }
        setHintByCountryCode();
        SharedPrefsUtil.putValue(this, Constants.CONTRYCODE, "contryCode", mCountryCode);

        LogUtils.i("-------------------------initData");

        username = SharedPrefsUtil.getValue(LoginActivity.this, Constants.USERNAME, "username", "");
        //显示上次登录的帐号
        if (username.length() > 0) {
            binding.loginClearPassWord.setVisibility(View.VISIBLE);
            binding.etLoginPhonenum.setText(username);
        }

        binding.btnLogin.setEnabled(false);
        binding.tbPasswordHide.setChecked(false);
        binding.etLoginPassword.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
        binding.etLoginPhonenum.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable editable) {
                LogUtils.i("-------------------------账号监听 :");
                boolean b = !"".equals(editable.toString().trim());
                if (b) {
                    binding.loginClearPassWord.setVisibility(View.VISIBLE);
                } else {
                    binding.loginClearPassWord.setVisibility(View.INVISIBLE);
                }

                if (!"".equals(binding.etLoginPassword.getText().toString().trim()) && b &&
                        binding.etLoginPassword.length() >= 6) {
                    binding.btnLogin.setEnabled(true);
                } else {
                    binding.btnLogin.setEnabled(false);
                }

            }
        });
        binding.etLoginPassword.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable editable) {

                if (!"".equals(binding.etLoginPhonenum.getText().toString().trim()) &&
                        !"".equals(editable.toString().trim()) &&
                        binding.etLoginPassword.length() >= 6) {
                    binding.btnLogin.setEnabled(true);
                } else {
                    binding.btnLogin.setEnabled(false);
                }
            }
        });

        binding.btnLogin.setOnClickListener(this);
        binding.tvForgetPassword.setOnClickListener(this);
        binding.tvRegister.setOnClickListener(this);
        binding.tbPasswordHide.setOnClickListener(this);
        binding.ivWeChatLoing.setOnClickListener(this);
        binding.rlLoginCountry.setOnClickListener(this);
        binding.loginClearPassWord.setOnClickListener(this);
        //跳槽免责声明弹窗
        policyPrivacyDialog();//小米上架必须要政策隐私弹框形式，不然审核不通过
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
        LogUtils.i("---------login----------------onDestroy");
    }

    @Override
    public void onClick(View v) {
        if (RomUtils.isFastClick()) {
            return;
        }
        switch (v.getId()) {
            case R.id.btn_login:
                //登录
                phoneOrEmail = binding.etLoginPhonenum.getText().toString().trim();
                String password = binding.etLoginPassword.getText().toString().trim();
                String contryCode = CountryCodeUtils.getCountryZipCode(this);
                if (password.isEmpty()) {
                    ToastUtil.show(this, getString(R.string.U_T_Pw_Null), Toast.LENGTH_LONG);
                    return;
                }
                //显示
                if (loadProgressDialog == null) {
                    loadProgressDialog = new LoadProgressDialog(this);
                }
                loadProgressDialog.show();
                //登录接口实现
                LoginParam param = new LoginParam();
                param.setAccount(phoneOrEmail);
                param.setLoginType(LoginParam.TYPE_PASSWORD);
                param.setCode(password);
                param.setCountryCode(mCountryCode);
                AppContext.getAccountService().login(param);

                break;
            case R.id.iv_WeChatLoing:
                //微信登录
                if (!WXapi.isWXAppInstalled()) {
//                    Toast.makeText(this, getString(R.string.install_WeChat), Toast.LENGTH_LONG).show();
                    return;
                }
                final SendAuth.Req req = new SendAuth.Req();
                req.scope = "snsapi_userinfo";
                req.state = "wechat_sdk_demo";
                WXapi.sendReq(req);
                LogUtils.i("微信登录-------------------------返回了: ");
                break;
            case R.id.tv_forget_password:
                //找回密码
                Intent_utils.enterIntent(this, RetrievePasswordActivity.class);
                break;
            case R.id.tv_register:
                //注册
                Intent_utils.enterIntent(this, RegisterActivity.class);
                break;
            case R.id.rl_loginCountry:
                Intent intenta = new Intent(this, CountryActivity.class);
                startActivityForResult(intenta, 1);
                break;
            case R.id.tb_password_hide:
                if (binding.tbPasswordHide.isChecked()) {
                    Log.d(TAG, "visible is checked " + binding.tbPasswordHide.isChecked());
                    binding.etLoginPassword.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                } else {
                    Log.d(TAG, "invisible is checked " + binding.tbPasswordHide.isChecked());
                    binding.etLoginPassword.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                }
                binding.etLoginPassword.setSelection(binding.etLoginPassword.getText().toString().trim().length());
                break;
            case R.id.login_clearPassWord:
                binding.etLoginPhonenum.setText("");
                break;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(Event event) {
        DialogUtils.dismissProgressDialog();
        if (event.getType() == Event.MESSAGE_TYPE_LOGIN) {
            if (loadProgressDialog != null) {
                loadProgressDialog.dismiss();
            }
            if (event.isResult()) {
                SharedPrefsUtil.putValue(this, Constants.NAME_USER, Constants.KEY_FIRST_LOGIN, true);
                //保存登录成功标记
                SharedPrefsUtil.putValue(LoginActivity.this, Constants.ISLOG, "isLog", true);
                //登录成功后保存登录帐号
                SharedPrefsUtil.putValue(LoginActivity.this, Constants.USERNAME, "username", phoneOrEmail);
                //保存
                SharedPrefsUtil.putValue(LoginActivity.this, Constants.USERNAME, "contryCode", mCountryCode);
                SharedPrefsUtil.putValue(LoginActivity.this, "isFirstRun", "isFirstRun", true);

                Intent_utils.enterIntent(LoginActivity.this, MainBottomTabActivity.class);
                finish();
            } else {
                LoginResponse response = (LoginResponse) event.getContent();
                if (response.getErrorCode() == LoginResponse.ERROR_NETWORK) {
                    ToastUtil.showShort(this, getString(R.string.U_UnknownErr));
                } else if (response.getErrorCode() == LoginResponse.ERROR_INCORRECT_PASSWORD) {
                    ToastUtil.showShort(this, getString(R.string.L_T_Un_Err));
                } else if (response.getErrorCode() == LoginResponse.ERROR_CODE_USER_NOT_EXIST) {
                    ToastUtil.showShort(this, getString(R.string.U_T_Un_No));
                } else if (response.getErrorCode() == LoginResponse.ERROR_SERVER) {
                    ToastUtil.showShort(this, getString(R.string.U_T_Server_Err));
                } else {
                    ToastUtil.showShort(this, getString(R.string.U_UnknownErr));
                }
            }
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == 1) {
            if (resultCode == 2) {
                String countryName = data.getStringExtra("countryName");
                String countryCode = data.getStringExtra("countryCode");
//                String zh = data.getStringExtra("zh");
//                String en = data.getStringExtra("en");
                LogUtils.i(countryName + "  : " + countryCode + "------------------------- aaaa: ");
                Constants.contryCode = countryCode;
                mCountryCode = countryCode;
                setHintByCountryCode();
                binding.tvCountrycodeCode.setText(countryName);
//                if ("中国".equals(countryName)) {
//                    binding.tvCountrycodeCode.setText(countryName);
//                } else {
//                    binding.tvCountrycodeCode.setText(en);
//                }
                SharedPrefsUtil.putValue(this, Constants.CONTRYCODE, "contryCode", mCountryCode);
            }
        }
//        else if (requestCode == 5) {
//            if (resultCode == 3) {
//                boolean tag = data.getBooleanExtra("tag", false);
//                if (!tag) {
//                    AtyContainer.getInstance().finishAllActivity(); //在登录界面点击返回键退出程序
//                }
//            }
//        }
    }

    //    点击菜单返回按钮,程序退到后退运行
    private long mExitTime;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            LogUtils.i("-------------------LoginActivity------ onKeyDown : ");
//            //与上次点击返回键时刻作差
//            if ((System.currentTimeMillis() - mExitTime) > 2000) {
//                //大于2000ms则认为是误操作，使用Toast进行提示
//                ToastUtil.show(LoginActivity.this, "再按一次退出程序", Toast.LENGTH_LONG);
//                //并记录下本次点击“返回键”的时刻，以便下次进行判断
//                mExitTime = System.currentTimeMillis();
//            } else {
//                //小于2000ms则认为是用户确实希望退出程序-调用System.exit()方法进行退出
//                AtyContainer.getInstance().finishAllActivity(); //在登录界面点击返回键退出程序
//            }
            AtyContainer.getInstance().finishAllActivity(); //在登录界面点击返回键退出程序
            return true;
        }
        return super.onKeyDown(keyCode, event);

    }

    private void setHintByCountryCode() {
        if (!mCountryCode.equals("86")) {
            binding.etLoginPhonenum.setHint(getString(R.string.MY_Email));
        } else {
            binding.etLoginPhonenum.setHint(getString(R.string.U_Un_Hint));
        }
    }

    /**
     * 政策隐私弹框
     */
    private void policyPrivacyDialog() {
        policyPrivacy_dialog = new Dialog(LoginActivity.this);
        policyPrivacy_dialog.setContentView(R.layout.disclaimer_dialog);
        policyPrivacy_dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
        policyPrivacy_dialog.setCancelable(false);
        policyPrivacy_dialog.setCanceledOnTouchOutside(false);

        TextView mTvConsent = policyPrivacy_dialog.findViewById(R.id.btn_agree);
        TextView mTvReject = policyPrivacy_dialog.findViewById(R.id.btn_reject);
        TextView mTvDisclaimerServer = policyPrivacy_dialog.findViewById(R.id.tv_disclaimerServer);
        TextView mTvDisclaimerPrivacy = policyPrivacy_dialog.findViewById(R.id.tv_disclaimerPrivacy);

        mTvDisclaimerServer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (RomUtils.isFastClick()) {
                    return;
                }
                Intent_utils.enterIntentContext(LoginActivity.this, ServerAndPrivacyActivity.class, "Server_Privacy", "Server");
            }
        });
        mTvDisclaimerPrivacy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (RomUtils.isFastClick()) {
                    return;
                }
                Intent_utils.enterIntentContext(LoginActivity.this, ServerAndPrivacyActivity.class, "Server_Privacy", "Privacy");
            }
        });


        mTvConsent.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (RomUtils.isFastClick()) {
                    return;
                }
                SharedPrefsUtil.putValue(LoginActivity.this, "ServerAndPrivacySign", "ServerAndPrivacySign", true);
                policyPrivacy_dialog.dismiss();

            }
        });
        mTvReject.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (RomUtils.isFastClick()) {
                    return;
                }
                SharedPrefsUtil.putValue(LoginActivity.this, "ServerAndPrivacySign", "ServerAndPrivacySign", false);
                policyPrivacy_dialog.dismiss();
                AtyContainer.getInstance().finishAllActivity(); //在登录界面点击返回键退出程序
            }
        });
        policyPrivacy_dialog.show();
    }
}
